<template>
  <div>
    <!-- 第一行：科目选择 -->
    <div class="flex items-center mb-4">
      <el-select
        v-model="selectedSubject"
        clearable
        placeholder="请选择科目"
        style="width: 180px"
        @change="fetchQuestions"
      >
        <el-option v-for="subject in subjects" :key="subject" :label="subject" :value="subject" />
      </el-select>
    </div>

    <div class="flex items-center space-x-4 mb-6">
      <el-input
        v-model="searchKeyword"
        clearable
        placeholder="搜索题干内容"
        style="width: 280px"
        @keyup.enter="fetchQuestions"
      />

      <el-button size="default" type="primary" @click="fetchQuestions"> 搜索 </el-button>
    </div>

    <el-table :data="questions" stripe style="width: 100%">
      <el-table-column label="ID" prop="questionId" width="80" />
      <el-table-column label="题干">
        <template #default="{ row }">
          <div v-html="renderMarkdown(row.content)"></div>
        </template>
      </el-table-column>
      <el-table-column label="科目" prop="subject" width="100" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="goToDetail(row.questionId)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-center mt-6">
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :total="total"
        background
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { AllSubjects, renderMarkdown } from '@/api/utils.ts'

const selectedSubject = ref<string | null>(null)
const searchKeyword = ref('')
const subjects = AllSubjects

const questions = ref<any[]>([])
const page = ref(1)
const pageSize = 10
const total = ref(0)
const router = useRouter()

const fetchQuestions = async () => {
  try {
    const params: Record<string, any> = {
      keyword: searchKeyword.value || undefined,
      subject: selectedSubject.value || undefined,
    }
    const response = await apiClient.get(`admin/approved-questions/${page.value}`, { params })

    questions.value = response.data.data
    total.value = response.data.total
  } catch (error) {
    handleErrorAndRedirect(error, '获取题目列表失败')
  }
}

const handlePageChange = (newPage: number) => {
  page.value = newPage
  fetchQuestions()
}

const goToDetail = (id: number) => {
  router.push({ name: 'QuestionDetail', params: { id } })
}

onMounted(fetchQuestions)
</script>
